import React, { PureComponent, Fragment } from 'react';
import {Checkbox} from 'antd';
import styles from './index.less';

/*
  需要传入的属性
  1、dataList     // table中的dataSource
  2、onSelectChange // table中的onSelectChange事件
  3、selectedRows   // table中的onSelectChange事件中的参数selectedRows
  4、condition   //table中禁用checkbox的条件
*/

export default class CheckAllBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isChecked:false,
      indeterminate:false
    }

  }
  componentDidMount(){
    this.props.onRef(this)
  }
  selectAll = () => { // 全选按钮是否选中
    const { dataList = [], onSelectChange, selectedRows = [], condition } = this.props;
    if(dataList.length){
      if(dataList.length === selectedRows.length){
        typeof onSelectChange === "function" && onSelectChange([],[]);
        this.setState({isChecked:false})
      }else{
        const dataListIndex = [];
        dataList.forEach(item=>{
          if(condition){
            if(!item[condition]) dataListIndex.push(item.Id)
          }else{
            dataListIndex.push(item.Id)
          }
        });
        //console.log(index)
        this.setState({isChecked:true})
        typeof onSelectChange === "function" && onSelectChange(dataListIndex,dataList)
      }
    }

  }
  onChange = (selectedRowKeys) => { // 暴露给父组件，根据父组件中table里的checkbox选中数量修改全选checkbox值
    const { dataList = [], condition } = this.props;
    if(dataList.length){
      const dataListIndex = [];
      dataList.forEach(item=>{
        if(condition){
          if(!item[condition]) dataListIndex.push(item.Id)
        }else{
          dataListIndex.push(item.Id)
        }
      });
      let isChecked = null
      if(dataListIndex.length === selectedRowKeys.length){
        isChecked=true
      }else{
        isChecked=false
      }
      //console.log(selectedRowKeys,dataListIndex)
      this.setState({ isChecked, indeterminate: selectedRowKeys.length && selectedRowKeys.length<dataListIndex.length});
    }
  }

  cancelChecked = () => {
    this.setState({indeterminate:false,isChecked:false})
  }


  render() {
    const { isChecked ,indeterminate} = this.state;
    return (
      <div className={styles.checkAll}>
        <Checkbox checked={isChecked} indeterminate={indeterminate} onChange={this.selectAll}>当页全选</Checkbox>
      </div>
    );
  }
}
